package com.js.blog.interceptor;

import com.js.blog.bean.User;
import com.js.blog.exception.BusinessException;
import com.js.blog.exception.OtherErrorCode;
import com.js.blog.service.UserService;
import com.js.blog.util.JwtAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yanglin
 * @create 2024-02-29 15:51 星期四
 * description:
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        
        //2、执行认证
        if (StringUtils.isEmpty(token)){    //表示没有对应的token值
            throw new BusinessException(OtherErrorCode.USER_NOT_LOGIN);
        }
        
        //3、获取token中的userId
        String id = JwtAuthentication.validateToken(token);
        if (StringUtils.isEmpty(id)){
            //表示未登录
            throw new BusinessException(OtherErrorCode.USER_NOT_LOGIN);
        }
        
        //4、根据token中解析的Id查数据库
        User user = userService.getById(Long.parseLong(id));
        if (user == null){
            //表示库中不存在对应的用户
            throw new BusinessException(OtherErrorCode.USER_NOT_LOGIN);
        }

        return true;
    }
}
